package com.slipper.core.file;

import com.slipper.core.file.vo.FileVO;
import com.slipper.exception.CommonException;
import com.slipper.util.Tool;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.InputStream;
import java.util.Base64;

@Configuration
public class FileServiceUtil {
    private static IFileService fileService = null;

    @Resource(name = "fileService")
    public void setCache(IFileService fileService) {
        FileServiceUtil.fileService = fileService;
    }

    private static IFileService getFileService() {
        return FileServiceUtil.fileService;
    }

    public static FileVO saveFile(String fileName, String base64) throws Exception {
        if (Tool.isBlank(base64)) throw new CommonException("文件不能为空！");
        return saveFile(fileName, Base64.getDecoder().decode(base64));
    }

    public static FileVO saveFile(String fileName, InputStream inputStream) throws Exception {
        if (inputStream == null) throw new CommonException("文件不能为空！");
        return saveFile(fileName, inputStream.readAllBytes());
    }

    public static FileVO saveFile(String fileName, byte[] bytes) throws Exception {
        return getFileService().saveFile(fileName, bytes);
    }

    public static FileVO saveFile(File file) throws Exception {
        if (file == null) throw new CommonException("文件不能为空！");
        return getFileService().saveFile(file);
    }

    public static void saveFileToPath(String path, byte[] bytes) throws Exception {
        getFileService().saveFileToPath(path, bytes);
    }

    public static byte[] readFile(String path) throws Exception {
        return getFileService().readFile(path);
    }

    public static String readFileToBase64(String path) throws Exception {
        return Base64.getEncoder().encodeToString(getFileService().readFile(path));
    }

    public static void readFile(String path, String range, HttpServletResponse response) throws Exception {
        getFileService().readFile(path, range, response);
    }
}
